import os
from datetime import datetime
from models import Session, UserAuditLog, CalculatorAuditLog

AUDIT_LOG_FILE = "user_audit_logs.json"

# ------------------- 用户管理审计日志 -------------------
def log_audit(action, username, target_user_id=None, details=None):
    """记录用户审计日志"""
    session = Session()
    try:
        log = UserAuditLog(
            action=action,
            username=username,
            target_user_id=target_user_id,
            details=details
        )
        session.add(log)
        session.commit()
    finally:
        session.close()

def get_audit_logs():
    """获取用户审计日志"""
    session = Session()
    try:
        logs = session.query(UserAuditLog).order_by(UserAuditLog.timestamp.desc()).all()
        return [
            {
                "timestamp": log.timestamp.isoformat(),
                "action": log.action,
                "username": log.username,
                "target_user_id": log.target_user_id,
                "details": log.details,
                "date": log.timestamp.strftime('%Y-%m-%d'),
                "time": log.timestamp.strftime('%H:%M:%S')
            }
            for log in logs
        ]
    finally:
        session.close()

# ------------------- 计算器审计日志 -------------------
def log_calc_audit(calc_id, action, username, details, old_value=None, new_value=None):
    """记录计算器审计日志"""
    session = Session()
    try:
        log = CalculatorAuditLog(
            calculator_id=calc_id,
            action=action,
            username=username,
            details=details,
            old_value=old_value,
            new_value=new_value
        )
        session.add(log)
        session.commit()
    finally:
        session.close()

def get_calc_audit_logs(calc_id=None):
    """获取计算器审计日志"""
    session = Session()
    try:
        query = session.query(CalculatorAuditLog)
        if calc_id:
            query = query.filter_by(calculator_id=calc_id)
        logs = query.order_by(CalculatorAuditLog.timestamp.desc()).all()
        return [
            {
                "timestamp": log.timestamp.isoformat(),
                "calc_id": log.calculator_id,
                "action": log.action,
                "username": log.username,
                "details": log.details,
                "old_value": log.old_value,
                "new_value": log.new_value,
                "date": log.timestamp.strftime('%Y-%m-%d'),
                "time": log.timestamp.strftime('%H:%M:%S')
            }
            for log in logs
        ]
    finally:
        session.close()
